/**
 * ReportGear(2011)
 */
package com.reportgear.report.model.calculator;

import java.util.Iterator;

import net.abbp.report.model.Cell;
import net.abbp.report.model.ReportModel;
import net.abbp.report.model.cell.style.Style;

import net.abbp.core.util.StringUtils;

/**
 * 清理空单元格
 * 
 * @version 1.0 2011-6-6
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class ClearCalculator extends AbstractCalculator {
    public ClearCalculator() {

    }

    @Override
    public ReportModel calculate(ReportModel model, CalcParameter parameter) {
        if (logger.isDebugEnabled()) {
            logger.debug("计算模型：清理单元格");
        }

        ReportModel calcModel = model;

        this.doCalculate(calcModel);

        return calcModel;
    }

    /**
     * 计算
     * 
     * @param model
     *            模型
     */
    private void doCalculate(ReportModel model) {
        boolean canDelete = true;
        for (int size = model.getColumnCount(), i = size - 1; i >= 0; i--) {
            for (Iterator<Cell> iter = model.getColumn(i); iter.hasNext();) {
                Cell cell = iter.next();
                if (!StringUtils.isEmpty(cell.getValue()) || cell.isMerged()
                        || !Style.DEFAULT_STYLE.equals(cell.getStyle())) {
                    canDelete = false;
                    break;
                }
            }

            if (canDelete) {
                model.removeColumn(i);
            } else {
                break;
            }
        }

        canDelete = true;
        for (int size = model.getRowCount(), i = size - 1; i >= 0; i--) {
            for (Iterator<Cell> iter = model.getRow(i); iter.hasNext();) {
                Cell cell = iter.next();
                if (StringUtils.isEmpty(cell.getValue()) && Style.DEFAULT_STYLE.equals(cell.getStyle())) {

                } else {
                    canDelete = false;
                    break;
                }
            }

            if (canDelete) {
                model.removeRow(i);
            } else {
                break;
            }
        }
    }
}
